using System;
using System.ComponentModel.Composition.Hosting;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace Mvc1.App_Start
{
    public class MefControllerFactory: DefaultControllerFactory
    {
        private readonly CompositionContainer _container;

        public MefControllerFactory(CompositionContainer container)
        {
            _container = container;
        }

        protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
        {
            if (controllerType == null)
            {
                throw new HttpException(404, "Not found.");
            }
            var controllers = _container.GetExports<IController>();
            var controllerExport = controllers.FirstOrDefault(x => x.Value.GetType() == controllerType);

            if (controllerExport == null)
            {
                return base.GetControllerInstance(requestContext, controllerType);
            }
            
            return controllerExport.Value;
        }
    }
}